import OpenAI from 'openai';

class APIService {
    constructor() {
        this.client = new OpenAI({
            baseURL: 'https://ai.gitee.com/v1',
            apiKey: 'RQMEA912OMGYETPJ80RQU2LTUCTLOLRH3OYOFTN2',
            defaultHeaders: {
                'X-Failover-Enabled': 'true'
            },
            dangerouslyAllowBrowser: true
        });
    }

    async translateClassic(text) {
        try {
            const response = await this.client.chat.completions.create({
                model: 'DeepSeek-R1-Distill-Qwen-14B',
                stream: false,
                max_tokens: 1024,
                temperature: 0.6,
                messages: [{
                        role: 'system',
                        content: '你是一名专业研究文言文的文学专家，可以根据输入的文言文翻译成现代文，并给出出自哪里，根据模版：翻译：……，出自：……，解析：……，进行翻译。'
                    },
                    {
                        role: 'user',
                        content: `请翻译并解析以下文言文：${text}`
                    }
                ]
            });
            const result = this._parseResponse(response);
            if (result.errors && result.errors.length) {
                throw new Error(result.errors.join(','));
            }
            return result;
        } catch (error) {
            console.error('翻译接口错误:', error);
            return {
                translation: '翻译服务暂时不可用',
                annotations: [],
                errors: ['网络连接异常']
            };
        }
    }

    _parseResponse(response) {
        const content = response.choices[0].message.content;

        // 新正则匹配模式
        const translationMatch = content.match(/翻译：([^，\n]+)/);
        const sourceMatch = content.match(/出自《([^》]+)/);
        const analysisMatch = content.match(/解析：([\s\S]+?)(?=\n\*\*|$)/);
        console.log('API响应原文：', content, sourceMatch);
        if (!translationMatch || !sourceMatch || !analysisMatch) {
            console.error('解析失败字段：', {
                translationMatch,
                sourceMatch,
                analysisMatch
            });
            return {
                translation: '解析失败',
                source: '未知出处',
                analysis: '',
                annotations: [],
                errors: ['响应格式不符合预期']
            };
        }

        return {
            translation: translationMatch[1].trim(),
            source: sourceMatch[1].trim(),
            analysis: analysisMatch[1].trim(),
            annotations: sourceMatch && sourceMatch.length > 1 ? [`出自《${sourceMatch[1]}》`] : [],
            errors: []
        };
    }
}

export const apiService = new APIService();